// BBR congestion control algorithm
// Based on Google's BBR (Bottleneck Bandwidth and RTT)

use super::CongestionController;
use std::time::Duration;

pub struct BbrCongestionController {
    bandwidth: u64,
    rtt: Duration,
    cwnd: usize,
}

impl BbrCongestionController {
    pub fn new() -> Self {
        Self {
            bandwidth: 0,
            rtt: Duration::from_millis(100),
            cwnd: 10,
        }
    }
}

impl Default for BbrCongestionController {
    fn default() -> Self {
        Self::new()
    }
}

impl CongestionController for BbrCongestionController {
    fn on_sent(&mut self, _bytes: usize, _now: Duration) {
        // BBR doesn't need to track sent packets in the same way
    }

    fn on_ack(&mut self, bytes: usize, rtt: Duration, _now: Duration) {
        // Update RTT estimate
        self.rtt = rtt;
        
        // Estimate bandwidth
        let bw = (bytes as f64 / rtt.as_secs_f64()) as u64;
        if bw > self.bandwidth {
            self.bandwidth = bw;
        }
        
        // Update congestion window
        self.cwnd += bytes;
    }

    fn on_loss(&mut self, _bytes: usize, _now: Duration) {
        // BBR is less aggressive on loss
        self.cwnd = (self.cwnd as f64 * 0.9) as usize;
    }

    fn can_send(&self) -> bool {
        true // BBR is pacing-based, always allows sending
    }

    fn bandwidth(&self) -> u64 {
        self.bandwidth
    }
}
